const express = require('express');
const router = express.Router();
const db = require('../config/database');
const { authenticateToken, encryptPhone, decryptPhone, getNextId, logUserOperation } = require('../untils/untils');
const dayjs = require('dayjs')
const { cryptoHelper } = require('../config/global');

router.get('/', authenticateToken, async (req, res) => {
    try {
        const { role_name } = req.query;
        let sql = `SELECT * FROM role`;
        if (role_name) {
            sql += ` WHERE role_name LIKE '%${role_name}%'`;
        }
        let [result] = await db.execute(sql);

        // 记录查询日志
        await logUserOperation(
            req,
            '查询',
            '角色管理',
            `查询角色列表${role_name ? '，筛选条件：' + role_name : ''}`
        );

        res.json({
            success: true,
            message: '获取角色列表成功',
            data: result
        });
    } catch (error) {
        console.error('获取角色列表失败:', error);

        // 记录失败日志
        await logUserOperation(
            req,
            '查询',
            '角色管理',
            `查询角色列表${role_name ? '，筛选条件：' + role_name : ''}`,
            '失败',
            error.message
        );

        res.status(500).json({
            success: false,
            message: '获取角色列表失败',
            error: error.message
        });
    }
});

router.put('/add', authenticateToken, async (req, res) => {
    try {
        const { role_name, permissions } = req.body;
        const permissions_string = permissions.join(',');
        const role_id = await getNextId('ROLE', 'role_id', 'role', 5);
        let sql = `INSERT INTO role (role_id, role_name,permissions) VALUES (?, ?, ?)`;
        let params = [role_id, role_name, permissions_string];
        const [result] = await db.execute(sql, params);

        // 记录添加日志
        await logUserOperation(
            req,
            '添加',
            '角色管理',
            `添加角色：${role_name}`
        );

        res.json({
            success: true,
            message: '添加角色成功',
            data: result
        });
    } catch (error) {
        console.error('添加角色失败:', error);

        // 记录失败日志
        await logUserOperation(
            req,
            '添加',
            '角色管理',
            `添加角色：${req.body.role_name}`,
            '失败',
            error.message
        );

        res.status(500).json({
            success: false,
            message: '添加角色失败',
            error: error.message
        });
    }
});

router.post('/update', authenticateToken, async (req, res) => {
    try {
        const { role_id, role_name, permissions } = req.body;
        const permissions_string = permissions.join(',');
        let sql = `UPDATE role SET role_name = ?, permissions = ? WHERE role_id = ?`;
        let params = [role_name, permissions_string, role_id];
        const [result] = await db.execute(sql, params);
        res.json({
            success: true,
            message: '修改角色成功',
            data: result
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '修改角色失败',
            error: error.message
        });
    }
});

router.delete('/delete', authenticateToken, async (req, res) => {
    try {
        const { role_id } = req.query;
        let sql = `DELETE FROM role WHERE role_id = ?`;
        let params = [role_id];
        const [result] = await db.execute(sql, params);
        res.json({
            success: true,
            message: '删除角色成功',
            data: result
        });
    } catch (error) {
        console.error('删除角色失败:', error);
        res.status(500).json({
            success: false,
            message: '删除角色失败',
            error: error.message
        });
    }
});


// 获取权限分配列表
router.get('/permissions', authenticateToken, async (req, res) => {
    try {
        const [result] = await db.execute('SELECT * FROM vue_routes');
        const new_result = result.filter(item => item.meta);
        new_result.forEach(item => {
            if (item.children) {
                item.children = item.children.filter(child => child.meta);
            }
        });


        // 组装一个树形结构 根据mate的class属性
        const tree = [
            {
                key: '全部',
                name: '全部',
                child: []
            }
        ];
        // 获取所有meta的class属性
        let class_mate = new_result.reduce((acc, item) => {
            item.key = item.meta.title;
            item.name = item.meta.title;
            if (acc[item.meta.class]) {
                acc[item.meta.class].push(item);
            } else {
                acc[item.meta.class] = [item];
            }
            return acc;
        }, {});

        Object.keys(class_mate).forEach(item => {
            tree[0].child.push({
                key: item,
                name: item,
                child: class_mate[item]
            });
        });

        res.json({
            success: true,
            message: '获取权限分配列表成功',
            data: tree
        });


    }
    catch (error) {
        console.error('获取权限分配列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取权限分配列表失败',
            error: error.message
        });
    }
});

module.exports = router;